//SetCookie("wjk_staffid", 1);
//SetCookie("wjk_storeid", 4);
//SetCookie("wjk_uid", 1030);

//var userid = getCookie("wjk_uid");
//var staffId = getCookie("wjk_staffid"); //员工ID
//var storeid = getCookie("wjk_storeid");
//var token = getCookie("token");

var userid = getCookies("wjk_staff","uid");
var staffId = getCookies("wjk_staff", "staffid"); //员工ID
var storeid = getCookies("wjk_staff", "storeid");
var token = getCookies("wjk_staff", "token");


//login();
//全局接口参数
var siteConfig = {
    //接口域名
    apiDomain: "http://weapp.711688.net.cn/api/",
    imgDomain: "http://static.711688.net.cn/",
    imgPath: {
        //头像路径
        avater: "http://static.711688.net.cn/upload/card/source/",
        blogImage: "http://static.711688.net.cn/upload/store/{storeid}/blog/thumb500_800/",
    },
    formatAvater: function (avater) {
        if (avater.indexOf("http") == 0) {
            return avater;
        }
        return this.imgPath.avater + avater;
    },
    formatBlogImage: function (logo) {
        if (logo == null || trim(logo) == "") return "";
        if (logo.indexOf("http") > -1) return logo;
        return this.imgPath.blogImage.replace("{storeid}", storeid) + logo;
    }
}

//全局的接口地址
var siteApiList = {
    //雷达-行为
    RadarList: siteConfig.apiDomain + "radar/BehaviorList",
    //雷达-人
    RadarManList: siteConfig.apiDomain + "radar/TimeList",
    //雷达详情
    TimeDetailList: siteConfig.apiDomain + "radar/TimeDetailList",
    //雷达时间详情
    BehaviorDetail: siteConfig.apiDomain + "radar/BehaviorDetail",
    //雷达-时间
    RadarTimeList: siteConfig.apiDomain + "radar/RadarTimeList",
    //通讯录-客户列表
    ClientList: siteConfig.apiDomain + "addressBook/ClientList",
    //通讯录-标签管理
    TagRelationList: siteConfig.apiDomain + "addressbook/GetTagRelationList",
    //通讯录-标签修改
    UpdateClientTag: siteConfig.apiDomain + "addressbook/UpdateClientTag",
    //获取客户对应的标签
    GetTagRelationListById: siteConfig.apiDomain + "adressbook/GetTagRelationListById",
    //通讯录-标签详情
    GetTagRelationListById: siteConfig.apiDomain + "addressbook/GetTagRelationListById",
    //更新客户的标签
    AddTagRelation: siteConfig.apiDomain + "addressbook/AddTagRelation",
    //通讯录-搜索
    GetCllientBySearch: siteConfig.apiDomain + "addressbook/GetCllientBySearch",
    //通讯录-添加跟进语
    AddClientFollow: siteConfig.apiDomain + "addressbook/AddClientFollow",
    //通讯录—获取跟进语列表
    GetClientFollowListPages: siteConfig.apiDomain + "addressbook/GetClientFollowListPages",
    //通讯录-获取通讯录列表
    GetClientFollowListPages: siteConfig.apiDomain + "addressbook/GetClientFollowListPages",
    //得到客户详细信息
    GetClient: siteConfig.apiDomain + "addressbook/GetClient",
    //得到客户详细信息
    GetClientInfo: siteConfig.apiDomain + "addressbook/GetClientInfo",
    //更改客户预计成交时间
    UpdateTradeDate: siteConfig.apiDomain + "addressBook/UpdateTradeDate",
    //更改客户预计成交概率
    UpdateProbability: siteConfig.apiDomain + "addressBook/UpdateProbability",
    //得到客户所有的标签
    GetTagRelationList: siteConfig.apiDomain + "addressBook/GetTagRelationList",
    //通讯录-跟进
    FollowUp: siteConfig.apiDomain + "addressBook/followup",
    //通讯录-客户人员添加
    AddClientTagRelations: siteConfig.apiDomain + "addressBook/AddClientTagRelations",
    //通讯录-客户关系添加
    AddTagRelation: siteConfig.apiDomain + "addressBook/AddTagRelation",
    //通讯录-互动跟进
    IM: siteConfig.apiDomain + "im.html",
    //员工信息
    GetInfo: siteConfig.apiDomain + "staff/getinfo",
    //修改员工信息
    UpdateStaff: siteConfig.apiDomain + "staff/UpdateStaff",
    //员工-修改个性签名
    UpdateSign: siteConfig.apiDomain + "staff/UpdateSign",
    //员工标签列表
    StaffTagList: siteConfig.apiDomain + "staff/StaffTagList",
    //删除员工标签
    DeleteStaffTag: siteConfig.apiDomain + "staff/DeleteStaffTag",
    //添加员工标签
    AddStaffTag: siteConfig.apiDomain + "staff/AddStaffTag",
    //获取自定义跟进语
    GetFollowTip: siteConfig.apiDomain + "staff/GetFollowTip",
    //添加自定义话语
    AddFollowTip: siteConfig.apiDomain + "staff/AddFollowTip",
    //删除自定义标签
    DeleteFollowTip: siteConfig.apiDomain + "staff/DeleteFollowTip",
    //员工动态
    BlogList: siteConfig.apiDomain + "blog/bloglist",
    //客户标签列表
    ClientTagList: siteConfig.apiDomain + "addressbook/ClientTagList",
    //添加客户标签
    AddClientTag: siteConfig.apiDomain + "addressbook/AddClientTag",
    //客户-互动消息
    ActionRecordList: siteConfig.apiDomain + "radar/ActionRecordList",
    //客户-AI分析
    ClientAnalysis: siteConfig.apiDomain + "addressbook/GetAnalysis",
    //客户-获取未添加的标签客户
    GetClientListByTag: siteConfig.apiDomain + "addressbook/GetClientListByTag",
    //我的-我的动态
    MyBlogList: siteConfig.apiDomain + "blog/MyBlogList",
    //我的-动态详情
    MyBlogDetail: siteConfig.apiDomain + "blog/BlogInfo",
    //我的-动态贴的评论
    BlogCommentList: siteConfig.apiDomain + "blog/BlogCommentList",
    //我的-设置欢迎语
    SetWelcomeTip: siteConfig.apiDomain + "staff/SetWelcomeTip",
    //我的-获取欢迎语
    GetWelcomeTip: siteConfig.apiDomain + "staff/GetWelcomeTip",
    //我的-添加欢迎语
    AddWelcomeTip: siteConfig.apiDomain + "staff/AddWelcomeTip",
    //我的-发表意见反馈
    AddFeedback: siteConfig.apiDomain + "Common/AddFeedback",
    //动态-添加评论
    AddBlogComment: siteConfig.apiDomain + "blog/AddBlogComment",
    //动态-发布动态
    AddBlog: siteConfig.apiDomain + "blog/AddBlog",
    //动态-动态点赞
    AddUp: siteConfig.apiDomain + "blog/AddUp",
    //动态-删除动态
    DeleteBlog: siteConfig.apiDomain + "blog/DeleteBlog",
    //上传头像
    UploadAvater: siteConfig.apiDomain + "tool/upload?operation=savecardavater",
    //上传商圈图片
    UploadBlogImage: siteConfig.apiDomain + "tool/upload?operation=uploadblogimage",
    //我的报表(AI销售)
    MyReport: siteConfig.apiDomain + "addressbook/GetMyReport",
    //我的报表-销售排行
    GetSalesList: siteConfig.apiDomain + "addressbook/GetSalesList",
    //boss 成交率漏斗
    GetTotalProbability: siteConfig.apiDomain + "addressbook/GetTotalProbability",
    //boss AI分析
    GetAnalysisByStaff: siteConfig.apiDomain + "addressbook/GetAnalysisByStaff",
}

//全局的html跳转地址
var siteUrlList = {
    //客户-标签管理
    ClientTagManager: "clientTagManager.html",
    //客户-搜索
    SearchLabel: "searchLabel.html",
    //客户-跟进
    FollowUp: "follow-up.html",
    //客户-客户资料
    ClientEdit: "client_edit.html",
    //客户-客户资料
    ClientTag: "clientTag.html",
    //员工标签
    StafTag: "mylabel.html",
    //boss报表
    BossReport: "bossRadar.html",
    //我的签名
    MySign: "mysign.html",
    //我的报表
    MyReport: "myRadar.html",
    //我的名片
    MyCard: "myCard.html",
    //我的动态
    MyBlog: "myBlog.html",
    //动态详情
    MyBlogDetail: "MyBlogDetail.html",
    //编辑我的资料
    EditInfo: "editorInfo.html",
    Feedback: "feedback.html",
    //设置欢迎语
    Setting: "setWelcome.html",
    //通讯录标签文字
    NewlBel: "newLabel.html",
    customerDetail: "customerDetail.html",
    //聊天-单聊窗口
    ImMessage: "../plugins/webim/msgflowlist.html",
    //聊天-消息列表
    ImMessageList: "../plugins/webim/message_list.html"
}



//全局的json状态码
var jsonCode = { success: 0, error: 501, NoData: 17 };


function $_2(id) {
    return document.getElementById(id);
}

/*URL参数*/
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = decodeURI(window.location.search).substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return "";
}

//删除左右两端的空格
function trim(str) {
    if (str == null) return "";
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

//跳转页面
function toUrl(url) {
    window.location.href = url;
}

//字符串是否空对象或者空值
function IsNullOrEmpty(str) {
    if (str == null || str == '')
        return true;
    return false;
}

//接口的数据是否正常
function isJsonSuccess(data) {
    if (data.Code == jsonCode.NotFound) {
        Alert("接口未找到 错误代码:404");
        return
    }
    if (data.Code != jsonCode.success) {
        Alert(data.Message);
        return false;
    }
    return true;
}

function isLogin() {
    if (staffId == null || userid == null || storeid == null || staffId == "" || storeid == "") {
        return false;
    }
    return true;
}


//自动微信登录
function AuthLogin() {
    return login();
}

// 登录状态验证
function login() {
    if (location.href.indexOf("error.html") == -1 && location.href.indexOf("loginout.html") == -1) {
        if (!isLogin()) {
            toUrl('/workwechat/oauthlogin');
            return false;
        }
    }
    return true;
}

//是否有AI权限 (0未开通, 1开通 )
function checkAiState() {
    var state = getCookies("wjk_staff", "aistate");
    alert(state + " # " + getCookie("wjk_staff"));
    if (state == 1)
        return true;
    else
        return false;
}

//是否有BOSS权限 (0未开通, 1开通 )
function checkBossState() {
    var state = getCookies("wjk_staff", "bossstate");
    if (state == 1)
        return true;
    else
        return false;
}

function GetDate(str) {
    if (str == null) return "";
    return str.replace("T", "");
}


//显示消息
function Alert(msg) {
    toast.show(msg);
}

//确认框
function confirmDialog(msg, callback) {
    var subject = "";
    var html = "";
    html += "<div class='js_dialog' id='confirmDialog' style='display:none'><div class='weui-mask'></div>"
    html += "<div class='weui-dialog'>"
    html += "<div class='weui-dialog__hd'><strong class='weui-dialog__title'>" + subject + "</strong></div>"
    html += "<div class='weui-dialog__bd'>" + msg + "</div>"
    html += "<div class='weui-dialog__ft'>"
    html += "<a href='javascript:;' class='weui-dialog__btn weui-dialog__btn_default confirmCacel'>取消</a>"
    html += "<a href='javascript:;' class='weui-dialog__btn weui-dialog__btn_primary confirmOk'>确认</a>"
    html += "</div></div></div>"
    $("body").append(html);
    $("#confirmDialog").fadeIn(200);
    $(".confirmCacel").click(function () { $("#confirmDialog").remove(); })
    $(".confirmOk").click(function () { $("#confirmDialog").remove(); callback() });
}

/********** 异步请求 start ************/
function ajaxGet(url, callBack) {
    Ajax(url, "", "GET", callBack);
}

function ajaxPost(url, param, callBack) {
    Ajax(url, param, "POST", callBack);
}

function Ajax(url, paramet, method, callBack) {
    wait.show("加载中");//显示等待框
    $.ajax({
        url: url,
        type: method,
        dataType: "json",
        data: encodeURI(paramet),
        success: function (json) {
            wait.dismiss();
            callBack(json);     //json方式回调
        },
        error: function (rs) {
            toast.show("请求异常!");
        }
    });
}

/********** 异步请求 end ************/


/********** Android提示框 start ************/
var toast = new Toast();
function Toast() {

    //提示框的html代码
    var _toast_html = '<div id="floatTS"><div style="width: 100%; height: 100%; background-color: Black; position: fixed;z-index:1000; opacity: 0.3;display:none;"></div><div style="width: 100%; height: 45px; left: 0; top: 50%; position: fixed; z-index:99999999999;"align="center"><div id="TStxt" style = "padding:10px; border-radius:5px; line-height:30px; background-color:Black; color:White; width:200px; display:block; opacity:0.8;"></div></div></div>';
    var maxOpacity = 100; //透明度的最大值
    var opacity = 0; //当前透明度值
    var tWaite = 1000; //弹出提示停留时间(毫秒)
    var tSpeed = 10; //提示框小时速度
    var disOpacity = 0.8; //显示时透明度值

    this.show = function (msg) {

        //先停止等待
        wait.dismiss();

        //方式三 
        if (self != top) {
            window.parent.window.toast.show(msg);//调用父窗口的toast对象
            return;
        }
        if ($("#TStxt").length < 1) {
            $("body").prepend(_toast_html);
        }
        else {
            $("#floatTS").css("display", "");
        }
        $("#TStxt").text(msg);
        if (opacity < 1) {
            opacity = maxOpacity;
            this.dismiss();
        } else {
            opacity = maxOpacity;
        }
    }

    //隐藏
    this.dismiss = function () {

        if (opacity < 0) {
            $("#floatTS").css("display", "none");
            return false;
        }
        $("#TStxt").css("opacity", opacity / maxOpacity * disOpacity);
        if (opacity == maxOpacity) {
            opacity--;
            setTimeout(function () { toast.dismiss(); }, tWaite);
        }
        else {
            opacity--;
            setTimeout(function () { toast.dismiss(); }, tSpeed);
        }
    }
}

/********** Android提示框 end ************/

/********** 等待对话框 start ************/

var wait = new WaitDialog();
function WaitDialog() {
    //等待框html代码
    var _wait_html = '<div id="floatWait"><div style="width: 100%; height: 100%; background-color: Black; position: fixed;z-index: 9999; opacity: 0.3;display:none;"></div><div style="width: 100%; height: 45px; left: 0; top: 50%; position: fixed; z-index: 1000;"align="center"><div style = "padding:10px; border-radius:5px; line-height:30px; background-color:Black; color:White; width:200px; display:block; opacity:0.8;"><span id = "msg"></span><span id="dot"></span></div></div></div>';
    this.isShow = false;
    this.show = function (msg) {
        if ($("#dot").length < 1) {
            $("body").prepend(_wait_html);
        }
        else {
            $("#floatWait").css("display", "");
        }
        $("#msg").text(msg);
        if (!this.isShow) {
            this.isShow = true;
            this.action();
        }
    }

    //动画
    this.action = function () {
        if ($("#dot").text().length > 5)
            $("#dot").text("·");
        else
            $("#dot").text($("#dot").text() + "·");

        if (this.isShow) {
            setTimeout(function () { wait.action(); }, 500);
        }
    }

    this.dismiss = function () {
        this.isShow = false;
        $("#floatWait").css("display", "none");
    }
}

/********** 等待对话框 start ************/

/********** 缓存 start ************/
//设置cookies
function SetCookie(name, value, Days) {
    if (Days == null) Days = 30; //设置Cookie有效时间
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
}

//获取cookie
function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]); return null;
}

function getCookies(name, key) {
    var values = "&" + getCookie(name);
    if (values != null) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
        var r = decodeURI(values).substr(1).match(reg);
        if (r != null)
            return trim(unescape(r[2]));
    }
    return "";
}

//删除cookies
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) {
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/";
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    }
}

//缓存到磁盘
function setStorage(key, value) {
    localStorage.setItem(key, value);
}

//读取缓存到磁盘的数据
function getStorage(key) {
    return localStorage.getItem(key);
}

//删除缓存
function delStorage(key) {
    if (key != null) {
        localStorage.removeItem(key);
    } else {
        localStorage.clear();
    }
}

//缓存到磁盘
function setSession(key, value) {
    sessionStorage.setItem(key, value);
}

//读取缓存到磁盘的数据
function getSession(key) {
    return sessionStorage.getItem(key);
}

//删除缓存
function delSession(key) {
    if (key != null) 
        sessionStorage.removeItem(key);
    else 
        sessionStorage.clear();
}
/********** 缓存 end ************/


//返回
function goBack() {
    var refurl = document.referrer.toString().toLocaleLowerCase();
    var backUrl = getQueryString("backurl");

    if (backUrl != null) {
        window.location.href = backUrl; //退回到上一页
        return;
    }

    if (refurl != null && refurl != '') {
        window.location.href = refurl;
        return;
    }

    window.location.href = 'index.html';
}

function isEmpty(data, msg) {
    //只输出错误消息
    if (data.code != jsonCode.success)
        msg = IsNullOrEmpty(msg) ? data.msg : msg;

    if (data.code != JsonCode.success) {
        Alert(msg);
        return true;
    }

    //列表没数据,显示接口msg
    if (data.code == jsonCode.NoData) {
        Alert(msg);
        return true;
    }

    //列表没数据,显示错误消息
    if (data.code == jsonCode.success && (data.item != null && data.item.length == 0) && msg != '') {
        Alert(msg);
        return true;
    }
    return false;
}

//分页控件
function getPager(callback, mescroll_id) {
    if (mescroll_id == null)
        mescroll_id = "mescroll";
    var mescroll = new MeScroll(mescroll_id, {
        down: {
            auto: false, //是否在初始化完毕之后自动执行下拉回调callback; 默认true
            use: false
        },
        up: {
            page: {
                num: 0, //当前页码,默认0,回调之前加1,即callback(page)从1开始;
                size: 1, //每页数据的数量; 
                time: null //加载第一页数据服务器返回的时间 (可空); 防止用户翻页时,后台新增了数据从而导致下一页数据重复;
            },
            offset: 50, //列表滚动到距离底部小于100px,即可触发上拉加载的回调
            auto: true, //初始化完毕,是否自动触发上拉加载的回调
            isBoth: false, //上拉加载时,如果滑动到列表顶部是否可以同时触发下拉刷新;默认false,两者不可同时触发; 这里为了演示改为true,不必等列表加载完毕才可下拉;
            callback: callback, //上拉加载的回调
            autoShowLoading: true
        }
    });
    return mescroll;
}

function isNoData(list) {
    if (list == null || list.length == 0)
        return true;
    return false;
}


function getNoDataMsg(page) {
    if (page != null && page > 1)
        return "<div class='no-data'>已经到底了</div>";
    return "<div class='no-data'>没有数据</div>";
}